import React, {useEffect, useState} from "react"
import {ArrowLeftOutlined} from "@ant-design/icons";
import {Form, Input, Button, PageHeader, message, Checkbox} from "antd";
import {postJSON, putJSON, get} from "../../../shared/server"
import ToolTipsInput from "../../../shared/libs/tooltips-input";

let timerId;

export default (props) => {
	const {history, match: {params}} = props;
	const isEdit = params.id && params.id >= 0;
	const [form] = Form.useForm();
	const [nameStatus, setNameStatus] = useState({});

	const layout = {
		labelCol: {span: 6},
		wrapperCol: {span: 16},
	};
	const tailLayout = {
		wrapperCol: {offset: 6, span: 16},
	};

	useEffect(() => {
		if (isEdit) {
			get(`/management/product/${params.id}`).then(data => {
				const {name, briefCode, fixedCostPrice, marketPrice, volatileCostPrice, otherCostPrice, remarks, description, itemNo} = data;
				form.setFieldsValue({
					itemNo,
					name,
					briefCode,
					fixedCostPrice,
					marketPrice,
					remarks,
					description,
					volatileCostPrice,
					otherCostPrice,
				})
			})
		}
	}, []);

	const onFinish = values => {
		if (isEdit) {
			putJSON(`/management/product/${params.id}`, values).then(result => {
				if (result) {
					message.success("更新成功")
					history.push("/app/product")
					setNameStatus({})
				}
			})
		} else {
			postJSON('/management/product', values).then(result => {
				if (result) {
					message.success("添加成功")
					if (values.continue) {
						form.resetFields();
						setNameStatus({})
					} else {
						history.push("/app/product");
					}
				}
			})
		}
	};

	const onFinishFailed = errorInfo => {
		console.log('Failed:', errorInfo);
	};

	const debounceDelay = (fn, wait = 0, value) => {
		if (timerId) {
			clearTimeout(timerId);
			timerId = null;
		}
		timerId = setTimeout(() => {
			fn(value);
		}, wait);
	}

	const generateBriefCodeDelay = (value) => {
		get(`/management/common/py`, {word: value}).then(result => {
			if (result) {
				form.setFieldsValue({
					briefCode: result,
				})
			}
		})
	}

	const generateBriefCode = (event) => {
		debounceDelay(generateBriefCodeDelay, 500, event.target.value)
	}

	const checkDuplicateItemNo = ({postData, callback}) => {
		get(`/management/product/itemNo/checkDuplicate`, postData).then(result => {
			if (result === true) {
				callback(`项目编号${postData.itemNo}已经存在,请使用其它编号!`)
			}
			callback()
		}).finally(() => setNameStatus({}))
	}

	const nameValidate = (rule, value, callback) => {
		setNameStatus({validateStatus: 'validating'})
		let postData = {
			itemNo: value,
		};
		if (isEdit) {
			postData = {
				...postData,
				id: params.id,
			}
		}
		debounceDelay(checkDuplicateItemNo, 500, {
			postData, callback
		});
	}

	const handleChange = (event) => {
		const value = event.target.value;
		value.replace(/[^\-?\d.]/g, '');
	}


	return (
		<div className="zr-panel">
			<div className="zr-panel-header">
				<PageHeader backIcon={<ArrowLeftOutlined/>}
				            onBack={() => window.history.back()} title={`${isEdit ? "编辑" : "新增"}产品`}
				            subTitle=""/>
			</div>
			<div className="zr-list-page-box body-bg body-border absolute">
				<div className="zr-table-box">
					<Form
						{...layout}
						style={{paddingTop: 20, width: 500, margin: "0 auto"}}
						form={form}
						name="basic"
						onFinish={onFinish}
						onFinishFailed={onFinishFailed}
					>
						<Form.Item
							label="项目名称"
							name="name"
							validateFirst={true}
							rules={[
								{required: true, message: "项目名称必须填写"},
							]}
						>
							<ToolTipsInput
								title="项目名称,最大50个字符"
								id="_name"
								placeholder="请输入项目名称"
								onChange={generateBriefCode}
							/>
						</Form.Item>
						<Form.Item
							label="项目编号"
							name="itemNo"
							hasFeedback
							{...nameStatus}
							validateFirst={true}
							rules={[
								{required: true, message: "项目编号必须填写"},
								{pattern: /^[A-Za-z0-9]+$/, message: "编号只能输入数字和字母"},
								{validator: nameValidate}
							]}
						>
							<ToolTipsInput
								title="项目编号,可输入最多20位数字和字母"
								id="_itemNo"
								placeholder="请输入项目编号"
							/>
						</Form.Item>
						<Form.Item
							label="项目简码"
							name="briefCode"
							validateFirst={true}
							rules={[
								{required: true, message: "项目简码必须填写"},
								{pattern: /^[A-Za-z0-9]+$/, message: "简码只能输入数字和字母"},
							]}
						>
							<ToolTipsInput title="项目简码,一般为项目名称拼音首字母" id="_briefCode" placeholder="请输入简码"/>
						</Form.Item>
						<Form.Item
							label="成本价"
							name="fixedCostPrice"
							validateFirst={true}
							rules={[
								{required: false, message: '成本价必须填写'},
								// /^\d+\.?\d*$/ 多位小数
								{pattern: /^\d+(\.\d{0,2})?$/, message: "请输入有效数字,且小数点后最多两位"}
							]}
						>
							<ToolTipsInput
								isPrice={true}
								title="项目固定成本价,有效金额格式,最多两位小数"
								id="_fixedCostPrice"
								placeholder="请输入成本价"
								style={{width: "100%"}}
								onChange={handleChange}
							/>
						</Form.Item>
						<Form.Item
							label="可变成本价"
							name="volatileCostPrice"
							validateFirst={true}
							rules={[{required: false, message: '可变成本价必须填写'},
								{pattern: /^\d+(\.\d{0,2})?$/, message: "请输入有效数字,且小数点后最多两位"}
							]}
						>
							<ToolTipsInput
								isPrice={true}
								title="项目可变成本价,有效金额格式,最多两位小数"
								id="_volatileCostPrice"
								placeholder="请输入可变成本价"
								style={{width: "100%"}}
							/>
						</Form.Item>
						<Form.Item
							label="其他成本价"
							name="otherCostPrice"
							validateFirst={true}
							rules={[{required: false, message: '其他成本价必须填写'},
								{pattern: /^\d+(\.\d{0,2})?$/, message: "请输入有效数字,且小数点后最多两位"}
							]}
						>
							<ToolTipsInput
								isPrice={true}
								title="项目其它成本价,有效金额格式,最多两位小数"
								id="_otherCostPrice"
								placeholder="请输入其他成本价"
								style={{width: "100%"}}
							/>
						</Form.Item>
						<Form.Item
							label="市场价"
							name="marketPrice"
							validateFirst={true}
							rules={[{required: false, message: "市场价必须填写"},
								{pattern: /^\d+(\.\d{0,2})?$/, message: "请输入有效数字,且小数点后最多两位"}
							]}
						>
							<ToolTipsInput
								isPrice={true}
								title="项目市场价(原价),有效金额格式,最多两位小数"
								id="_marketPrice"
								placeholder="请输入市场价"
								style={{width: "100%"}}
							/>
						</Form.Item>
						<Form.Item
							label="说明"
							name="description"
							rules={[{required: false, message: '备注!'}]}
						>
							<Input.TextArea placeholder={'项目描述,500字以内(业务员可见)'}/>
						</Form.Item>
						<Form.Item
							label="备注"
							name="remarks"
							rules={[{required: false, message: '备注!'}]}
						>
							<Input.TextArea placeholder={'项目备注,500字以内(仅管理员可见)'}/>
						</Form.Item>
						{
							isEdit
								? null
								: <Form.Item
									{...tailLayout}
									name="continue"
									valuePropName="checked"
									rules={[{required: false, message: '是否继续添加'}]}
								>
									<Checkbox>连续添加</Checkbox>
								</Form.Item>
						}
						<Form.Item {...tailLayout}>
							<Button type="primary" htmlType="submit">确认</Button>
							<Button style={{marginLeft: 10}} onClick={() => window.history.back()}>
								返回
							</Button>
						</Form.Item>
					</Form>
				</div>
			</div>
		</div>
	)
}